<template>
  <div class="system-settings">
    <div class="module-container">
      <div class="module-header">
        <icon name="cog" class="header-icon"></icon>
        <span class="header-title">系统设置</span>
      </div>
      <div class="module-content">
        <!-- 板块切换按钮 -->
        <dv-border-box-12 class="content-box">
          <el-tabs v-model="activeTab" type="card" class="custom-tabs">
            <el-tab-pane label="用户管理" name="userManagement" class="nav-tab-item">
              <div slot="label" class="custom-tab-label">
                <i class="el-icon-user"></i>
                <span>用户管理</span>
              </div>
              <el-card class="user-list-card">
                <div class="user-list-header">
                  <div class="user-list-title">
                    <i class="el-icon-user"></i>
                    <span>用户管理</span>
                  </div>
                  <el-button type="primary" icon="el-icon-plus" class="add-user-btn" @click="handleAddUser">添加用户</el-button>
                </div>
                <el-table
                  :data="userList"
                  class="user-list-table"
                  header-cell-class-name="user-list-table-header"
                  cell-class-name="user-list-table-cell"
                  style="width: 100%;"
                  v-loading="userListLoading"
                  empty-text="暂无用户数据"
                  border={false}
                >
                  <el-table-column label="序号" width="80" align="center">
                    <template #default="scope">{{ scope.$index + 1 }}</template>
                  </el-table-column>
                  <el-table-column prop="username" label="用户名" min-width="120"/>
                  <el-table-column prop="role" label="角色" min-width="100">
                    <template #default="scope">
                      <el-tag :type="getRoleTagType(scope.row.role)" class="custom-tag">{{ scope.row.role }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="lastLogin" label="最后登录时间" min-width="160"/>
                  <el-table-column prop="status" label="状态" min-width="80">
                    <template #default="scope">
                      <el-tag :type="scope.row.status === '可用' ? 'success' : 'danger'" class="custom-tag">{{ scope.row.status }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" min-width="140">
                    <template #default="scope">
                      <el-button size="mini" class="custom-mini-button" @click="handleEditUser(scope.row)">编辑</el-button>
                      <el-button size="mini" type="danger" class="custom-mini-danger-button" @click="handleDeleteUser(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-tab-pane>
            <el-tab-pane label="数据管理" name="dataManagement" class="nav-tab-item">
              <div slot="label" class="custom-tab-label">
                <i class="el-icon-document"></i>
                <span>数据管理</span>
              </div>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-card class="custom-card">
                    <div class="card-header">
                      <span class="card-title">数据导入</span>
                    </div>
                    <div class="data-import-content">
                      <div class="file-upload-section">
                        <p class="section-label">选择数据文件</p>
                        <el-upload
                          class="upload-demo"
                          action="#"
                          :auto-upload="false"
                          :on-change="handleFileChange"
                          :file-list="importFileList">
                          <el-button slot="trigger" size="small" type="primary" class="custom-button">选择文件</el-button>
                          <div slot="tip" class="el-upload__tip">未选择文件</div>
                        </el-upload>
                        <el-button type="primary" class="custom-button import-btn" @click="handleImportData" :loading="importLoading">导入数据</el-button>
                      </div>
                    </div>
                  </el-card>

                  <el-card class="custom-card" style="margin-top: 20px;">
                    <div class="card-header">
                      <span class="card-title">数据还原</span>
                    </div>
                    <div class="data-restore-content">
                      <div class="file-upload-section">
                        <p class="section-label">选择备份文件</p>
                        <el-upload
                          class="upload-demo"
                          action="#"
                          :auto-upload="false"
                          :on-change="handleRestoreFileChange"
                          :file-list="restoreFileList">
                          <el-button slot="trigger" size="small" type="primary" class="custom-button">选择文件</el-button>
                          <div slot="tip" class="el-upload__tip">未选择文件</div>
                        </el-upload>
                        <el-button type="primary" class="custom-button restore-btn" @click="handleRestoreData" :loading="restoreLoading">还原数据</el-button>
                      </div>
                    </div>
                  </el-card>

                  <el-card class="custom-card" style="margin-top: 20px;">
                    <div class="card-header">
                      <span class="card-title">数据更新</span>
                    </div>
                    <div class="data-update-content">
                      <el-button 
                        type="primary" 
                        class="custom-button update-btn" 
                        @click="handleUpdateFilterLevel" 
                        :loading="updateFilterLoading"
                      >
                        个人档案筛选条件更新等级
                      </el-button>
                      <el-button 
                        type="primary" 
                        class="custom-button update-btn" 
                        @click="handleUpdateScoreRank" 
                        :loading="updateScoreLoading"
                      >
                        个人评分及排名更新
                      </el-button>
                    </div>
                  </el-card>
                </el-col>

                <el-col :span="12">
                  <el-card class="custom-card">
                    <div class="card-header">
                      <span class="card-title">数据备份</span>
                    </div>
                    <div class="data-backup-content">
                      <p class="backup-frequency-label">备份频率</p>
                      <el-select v-model="backupFrequency" placeholder="请选择备份频率" class="backup-frequency-select">
                        <el-option label="每天" value="daily"></el-option>
                        <el-option label="每周" value="weekly"></el-option>
                        <el-option label="每月" value="monthly"></el-option>
                      </el-select>
                      <el-button type="primary" class="custom-button backup-btn" @click="handleBackupData" :loading="backupLoading">立即备份</el-button>
                    </div>
                  </el-card>

                  <el-card class="custom-card" style="margin-top: 20px;">
                    <div class="card-header">
                      <span class="card-title">数据清理</span>
                    </div>
                    <div class="data-clean-content">
                      <div class="clean-options">
                        <el-checkbox v-model="cleanOptions.users">清理用户数据</el-checkbox>
                        <el-checkbox v-model="cleanOptions.settings">清理系统设置</el-checkbox>
                      </div>
                      <el-button type="danger" class="custom-danger-button clean-btn" @click="handleCleanData" :loading="cleanLoading">清理数据</el-button>
                    </div>
                  </el-card>

                  <el-card class="custom-card" style="margin-top: 20px;">
                    <div class="card-header">
                      <span class="card-title">数据导出</span>
                    </div>
                    <div class="data-export-content">
                      <el-form :model="exportForm" label-width="100px" class="export-form">
                        <el-form-item label="数据类型">
                          <el-checkbox-group v-model="exportForm.dataTypes">
                            <el-checkbox label="study">学习</el-checkbox>
                            <el-checkbox label="life">生活</el-checkbox>
                            <el-checkbox label="health">健康</el-checkbox>
                            <el-checkbox label="social">社交</el-checkbox>
                            <el-checkbox label="thought">思想</el-checkbox>
                          </el-checkbox-group>
                        </el-form-item>
                        <el-form-item>
                          <el-button type="primary" class="custom-button export-btn" @click="handleExportData" :loading="exportLoading">导出数据</el-button>
                        </el-form-item>
                      </el-form>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="系统参数" name="systemParameters" class="nav-tab-item">
              <div slot="label" class="custom-tab-label">
                <i class="el-icon-setting"></i>
                <span>系统参数</span>
              </div>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-card class="custom-card">
                    <div class="card-header">
                      <span class="card-title">微信小程序设置</span>
                    </div>
                    <el-form :model="wxMiniForm" label-width="120px" class="param-form">
                      <el-form-item label="AppID">
                        <el-input v-model="wxMiniForm.appId" placeholder="请输入小程序AppID" show-password></el-input>
                      </el-form-item>
                      <el-form-item label="AppSecret">
                        <el-input v-model="wxMiniForm.appSecret" placeholder="请输入小程序AppSecret" show-password></el-input>
                      </el-form-item>
                      <el-form-item label="小程序名称">
                        <el-input v-model="wxMiniForm.name" placeholder="请输入小程序名称"></el-input>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" class="custom-button" @click="saveWxMiniSettings">保存设置</el-button>
                      </el-form-item>
                    </el-form>
                  </el-card>
                </el-col>
                <el-col :span="12">
                  <el-card class="custom-card">
                    <div class="card-header">
                      <span class="card-title">接口设置</span>
                    </div>
                    <el-form :model="apiForm" label-width="120px" class="param-form">
                      <el-form-item label="API地址">
                        <el-input v-model="apiForm.adress" placeholder="请输入API地址"></el-input>
                      </el-form-item>
                      <el-form-item label="API密钥">
                        <el-input v-model="apiForm.secretKey" placeholder="请输入API密钥" show-password></el-input>
                      </el-form-item>
                      <el-form-item label="模型">
                        <el-select v-model="apiForm.model" placeholder="请选择模型">
                          <el-option label="DeepSeek-v3" value="DeepSeek-v3"></el-option>
                          <el-option label="GPT-4" value="GPT-4"></el-option>
                          <el-option label="GPT-3.5" value="GPT-3.5"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" class="custom-button" @click="saveApiSettings">保存设置</el-button>
                      </el-form-item>
                    </el-form>
                  </el-card>
                </el-col>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </dv-border-box-12>
      </div>
    </div>
    <!-- 用户编辑对话框 -->
    <el-dialog :title="editUserForm.id ? '编辑用户' : '添加用户'" :visible.sync="editUserDialogVisible" width="40%">
      <el-form :model="editUserForm" :rules="editUserRules" ref="editUserForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserForm.username" :disabled="!!editUserForm.id"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editUserForm.password" type="password" placeholder="编辑时留空表示不修改密码"></el-input>
        </el-form-item>
        <el-form-item label="角色权限" prop="role">
          <el-select v-model="editUserForm.role" placeholder="请选择角色权限">
            <el-option v-for="item in mainRoleOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- 分支下拉框 -->
        <el-form-item v-if="editUserForm.role==='student'" label="骨干分组" prop="branchRole">
          <el-select v-model="editUserBranchRole" placeholder="请选择分组">
            <el-option v-for="item in studentBranchOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editUserForm.role==='teacher'" label="班主任分组" prop="branchRole">
          <el-select v-model="editUserBranchRole" placeholder="请选择分组">
            <el-option v-for="item in teacherBranchOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号状态" prop="status">
          <el-select v-model="editUserForm.status" placeholder="请选择状态">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" class="custom-button" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 数据清理对话框 -->
    <el-dialog title="数据清理" :visible.sync="cleanDialogVisible" width="40%">
      <el-alert
        title="警告：数据清理将隐藏历史数据，只显示当前学年数据，此操作不可逆！"
        type="warning"
        :closable="false"
        show-icon>
      </el-alert>
      <div style="margin-top: 20px; text-align: center;">
        <p>确定要执行数据清理操作吗？</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cleanDialogVisible = false">取 消</el-button>
        <el-button type="danger" class="custom-danger-button" :loading="cleanLoading" @click="confirmClean">确认清理</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';


export default {
  name: 'SystemSettings',
  computed: {
    // 获取选中数据类型的详细选项
    exportDataTypeOptions() {
      if (!this.exportForm.dataTypes || this.exportForm.dataTypes.length === 0) {
        return [];
      }

      // 合并所有选中数据类型的选项
      let options = [];
      this.exportForm.dataTypes.forEach(type => {
        if (this.moduleDataTypes[type]) {
          options = options.concat(this.moduleDataTypes[type]);
        }
      });

      return options;
    }
  },
  created() {
    // 页面创建时加载初始数据
    this.loadInitialData();
  },
  data() {
    return {
      activeTab: 'userManagement',
      userQueryForm: {
        username: ''
      },
      pageNum: 1,
      pageSize: 10,
      userList: [
        // 示例数据
        { username: 'admin', role: '管理员', status: '可用', lastLogin: '2023-10-01 12:00:00' },
        { username: 'user1', role: '普通用户', status: '禁用', lastLogin: '2023-09-30 10:00:00' }
      ],
      roleOptions: [
        { value: 'admin', label: '管理员' },
        { value: 'leader', label: '领导' },
        { value: 'backbone', label: '骨干' },
        { value: 'teacher', label: '专业班主任' },
        { value: 'user', label: '普通用户' },
        { value: 'freshmanadmin', label: '新生管理员' }
      ],
      statusOptions: [
        { value: 'active', label: '可用' },
        { value: 'inactive', label: '禁用' }
      ],
      // 角色映射表
      roleMap: {
        1: '管理员',
        2: '学员骨干：第一组',
        3: '学员骨干：第二组',
        4: '学员骨干：第三组',
        5: '新生管理员',
        6: '专业班主任：ZC',
        7: '专业班主任：SS',
        8: '专业班主任：XG',
        9: '专业班主任：RG',
        10: '专业班主任：TX',
        11: '领导',
        12: '新生管理员'
      },
      // 状态映射表
      statusMap: {
        1: '可用',
        0: '禁用'
      },
      // 微信小程序设置
      wxMiniForm: {
        appId: '',
        appSecret: '',
        name: ''
      },
      // API接口设置
      apiForm: {
        adress: 'http://api.example.com',
        secretKey: '',
        model: 'deepseek-r1'
      },
      // 数据管理相关
      exportLoading: false,
      importLoading: false,
      backupLoading: false,
      restoreLoading: false,
      cleanLoading: false,
      // 文件上传相关
      importFileList: [],
      restoreFileList: [],
      // 备份频率
      backupFrequency: 'daily',
      // 清理选项
      cleanOptions: {
        users: false,
        settings: false
      },
      // 导出表单
      exportForm: {
        dataTypes: [], // 多选数据类型
      },
      moduleDataTypes: {
        学习: [
          { label: '主动回答问题', value: 'proactive' },
          { label: '竞赛情况', value: 'competition' },
          { label: '图书馆使用', value: 'library' },
          { label: '作业评级', value: 'homework' },
          { label: '成绩对比', value: 'score' }
        ],
        生活: [
          { label: '请假缺勤', value: 'leave' },
          { label: '饭卡信息', value: 'mealcard' },
          { label: '内务信息', value: 'housekeeping' },
          { label: '外出信息', value: 'out' }
        ],
        作风养成: [
          { label: '军容风纪', value: 'jrfj' },
          { label: '纠察记录', value: 'picket' },
          { label: '保密检查', value: 'security' }
        ],
        健康: [
          { label: '体测数据', value: 'sportstest' },
          { label: '988就诊', value: 'visitdoctor' }
        ],
        社交: [
          { label: '参与活动', value: 'activities' },
          { label: '自主学术讲座', value: 'lecture' },
          { label: '公差勤务', value: 'business' },
          { label: '晚加班', value: 'overtime' }
        ]
      },
      // 对话框控制
      editUserDialogVisible: false,
      editUserForm: {
        id: '',
        username: '',
        password: '',
        status: ''
      },
      editUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      cleanDialogVisible: false,
      updateFilterLoading: false,
      updateScoreLoading: false,
      // 角色主选项
      mainRoleOptions: [
        { value: '1', label: '管理员' },
        { value: '11', label: '领导' },
        { value: 'student', label: '学生骨干' },
        { value: 'teacher', label: '专业班主任' },
        { value: 'freshmanadmin', label: '新生管理员' }
      ],
      // 学生骨干分支
      studentBranchOptions: [
        { value: '2', label: '第一组' },
        { value: '3', label: '第二组' },
        { value: '4', label: '第三组' }
      ],
      // 专业班主任分支
      teacherBranchOptions: [
        { value: '5', label: 'WD' },
        { value: '6', label: 'ZC' },
        { value: '7', label: 'SS' },
        { value: '8', label: 'XG' },
        { value: '9', label: 'RG' },
        { value: '10', label: 'TX' }
      ],
      // 编辑表单分支选择
      editUserBranchRole: '',
    }
  },
  methods: {
    // 用户角色标签类型
    getRoleTagType(role) {
      switch(role) {
        case '管理员': return 'danger';
        case '领导': return 'warning';
        case '骨干': return 'success';
        case '专业班主任': return 'info';
        case '新生管理员': return 'primary';
        default: return '';
      }
    },

    // 将角色代码转换为显示名称
    getRoleName(roleCode) {
      switch(roleCode) {
        case 'admin': return '管理员';
        case 'leader': return '领导';
        case 'backbone': return '骨干';
        case 'teacher': return '专业班主任';
        case 'user': return '普通用户';
        case 'freshmanadmin':
        case '5':
        case 5:
          return '新生管理员';
        default: return '未知角色';
      }
    },

    // 查询用户
    async onQueryUser() {
      try {
        const response = await this.$userapi.getUserList({ pageNum: this.pageNum, pageSize: this.pageSize });
        if (response.code === '200') {
          const userArr = response.data && response.data.userList ? response.data.userList : [];
          this.userList = userArr.map(user => ({
            id: user.id,
            username: user.username,
            role: this.roleMap[user.role] || user.role,
            roleCode: user.role,
            status: this.statusMap[user.status] || user.status,
            statusCode: user.status,
            lastLogin: this.formatDateTime(user.lastlogintime)
          }));
          this.$message.success(response.msg || `查询到${this.userList.length}条用户数据`);
        } else {
          this.$message.error(response.msg || '查询用户失败');
        }
      } catch (error) {
        console.error('查询用户出错:', error);
        this.$message.error('查询用户出错');
      }
    },

    // 格式化时间
    formatDateTime(val) {
      if (!val || val.length !== 14) return val || '从未登录';
      return `${val.substr(0,4)}-${val.substr(4,2)}-${val.substr(6,2)} ${val.substr(8,2)}:${val.substr(10,2)}:${val.substr(12,2)}`;
    },

    // 添加用户
    handleAddUser() {
      this.editUserForm = {
        id: '',
        username: '',
        password: '',
        role: '1',
        status: '1'
      };
      this.editUserBranchRole = '';
      this.editUserDialogVisible = true;
    },

    // 编辑用户
    handleEditUser(user) {
      this.editUserForm = {
        id: user.id,
        username: user.username,
        password: '', // 不回显密码
        role: user.roleCode == 1 || user.roleCode == 11 ? String(user.roleCode)
              : [2,3,4].includes(Number(user.roleCode)) ? 'student'
              : [5,6,7,8,9,10].includes(Number(user.roleCode)) ? 'teacher'
              : '',
        status: user.statusCode
      };
      if ([2,3,4].includes(Number(user.roleCode))) {
        this.editUserBranchRole = String(user.roleCode);
      } else if ([5,6,7,8,9,10].includes(Number(user.roleCode))) {
        this.editUserBranchRole = String(user.roleCode);
      } else {
        this.editUserBranchRole = '';
      }
      this.editUserDialogVisible = true;
    },

    // 保存用户（添加或编辑）
    async saveUser() {
      try {
        await this.$refs.editUserForm.validate();
        let finalRole = '';
        if (this.editUserForm.role === 'student' || this.editUserForm.role === 'teacher') {
          finalRole = this.editUserBranchRole;
        } else if (this.editUserForm.role === 'freshmanadmin') {
          finalRole = '5';
        } else {
          finalRole = this.editUserForm.role;
        }
        const userData = {
          id: this.editUserForm.id,
          username: this.editUserForm.username,
          password: this.editUserForm.password,
          role: String(finalRole),
          status: String(this.editUserForm.status),
          lastlogintime: this.editUserForm.lastlogintime ? String(this.editUserForm.lastlogintime) : ''
        };
        console.log('提交用户数据:', userData);
        let response;
        if (this.editUserForm.id) {
          response = await this.$userapi.updateUser(userData);
        } else {
          response = await this.$userapi.saveUser(userData);
        }
        const code = response.code || (response.data && response.data.code);
        const msg = response.msg || (response.data && response.data.msg);
        if (code === '200') {
          this.$message.success(this.editUserForm.id ? '用户更新成功' : '用户添加成功');
          this.editUserDialogVisible = false;
          this.onQueryUser();
        } else {
          this.$message.error(msg || (this.editUserForm.id ? '用户更新失败' : '用户添加失败'));
        }
      } catch (error) {
        if (error !== 'cancel' && error.message !== 'validation failed') {
          console.error('保存用户出错:', error);
          this.$message.error('保存用户出错');
        }
      }
    },

    // 删除用户
    handleDeleteUser(user) {
      this.$confirm(`确认删除用户 ${user.username}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await this.$userapi.deleteUser(user.id);
          if (response.code === '200') {
            this.$message.success('用户删除成功');
            this.onQueryUser(); // 刷新用户列表
          } else {
            this.$message.error(response.msg || '用户删除失败');
          }
        } catch (error) {
          console.error('删除用户出错:', error);
          this.$message.error('删除用户出错');
        }
      }).catch(() => {
        // 取消删除
      });
    },

    // 数据导入
    async handleImportData() {
      if (this.importFileList.length === 0) {
        this.$message.warning('请选择要导入的Excel文件');
        return;
      }
      this.importLoading = true;
      try {
        const file = this.importFileList[0].raw; // 获取原始文件对象
        const formData = new FormData();
        formData.append('file', file);
        const response = await this.$settingapi.importExcelData(formData);
        if (response.code === '200') {
          this.$message.success('数据导入成功');
          this.importFileList = []; // 清空文件列表
        } else {
          this.$message.error(response.msg || '数据导入失败');
        }
      } catch (error) {
        console.error('数据导入失败:', error);
        this.$message.error('数据导入失败');
      } finally {
        this.importLoading = false;
      }
    },

    // 数据备份
    async handleBackupData() {
      this.backupLoading = true;
      try {
        // 直接调用axios请求，以便更灵活地处理responseType
        const response = await this.$settingapi.backupDatabase();

        // 检查HTTP状态码和response.data是否为Blob
        if (response.status === 200 && response.data instanceof Blob) {
          // 成功获取Blob数据，处理下载
          const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          const now = new Date();
          const timestamp = `${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`;
          link.download = `数据库备份_${timestamp}.xlsx`;
          link.click();
          URL.revokeObjectURL(link.href);
          this.$message.success('数据备份成功');
        } else {
          // 如果不是200或不是Blob，尝试读取文本错误信息
          const reader = new FileReader();
          reader.onload = (e) => {
            try {
              const errorData = JSON.parse(e.target.result);
              this.$message.error(errorData.msg || `数据备份失败: ${response.status}`);
            } catch (parseError) {
              this.$message.error(`数据备份失败，无法解析错误信息 (${response.status})`);
            }
          };
          // 确保response.data是Blob，以便FileReader读取。如果response.data不是Blob，这里仍然会出错。
          // 更安全的做法是，如果response.data不是Blob，直接显示通用的失败信息，不尝试读取。
          // 考虑到之前的TypeError，直接处理非Blob情况更安全。
           this.$message.error(response.data && response.data.msg ? response.data.msg : `数据备份失败 (${response.status})`);
        }
      } catch (error) {
        console.error('数据备份失败:', error);
        // 这里的error是axios抛出的错误，通常在非2xx状态码时触发
        if (error.response && error.response.data) {
          // 如果错误响应包含数据，尝试读取
          const reader = new FileReader();
          reader.onload = (e) => {
            try {
              const errorData = JSON.parse(e.target.result);
              this.$message.error(errorData.msg || `数据备份失败 (${error.response.status})`);
            } catch (parseError) {
              this.$message.error(`数据备份失败，无法解析错误信息 (${error.response.status})`);
            }
          };
          // 如果error.response.data是Blob（因为responseType是blob），需要用FileReader读取
          // 如果error.response.data是其他类型（如字符串），直接显示
          if (error.response.data instanceof Blob) {
             reader.readAsText(error.response.data); // 尝试读取Blob中的文本错误信息
          } else if (typeof error.response.data === 'string') {
             this.$message.error(error.response.data);
          } else {
             this.$message.error(`数据备份失败 (${error.response.status})`);
          }
        } else {
          // 没有错误响应数据，显示通用错误
          this.$message.error('数据备份失败，网络或服务器错误');
        }
      } finally {
        this.backupLoading = false;
      }
    },

    // 数据还原
    async handleRestoreData() {
      if (this.restoreFileList.length === 0) {
        this.$message.warning('请选择要还原的备份文件');
        return;
      }
      this.restoreLoading = true;
      try {
        const file = this.restoreFileList[0].raw; // 获取原始文件对象
        const formData = new FormData();
        formData.append('file', file);
        const response = await this.$settingapi.restoreData(formData);
        if (response.code === '200') {
          this.$message.success('数据还原成功');
          this.restoreFileList = []; // 清空文件列表
        } else {
          this.$message.error(response.msg || '数据还原失败');
        }
      } catch (error) {
        console.error('数据还原失败:', error);
        this.$message.error('数据还原失败');
      } finally {
        this.restoreLoading = false;
      }
    },

    // 数据清理
    handleCleanData() {
      this.cleanDialogVisible = true;
    },

    // 确认清理数据
    async confirmClean() {
      let flag = '';
      if (this.cleanOptions.users && this.cleanOptions.settings) {
        flag = 'C'; // 清除所有
      } else if (this.cleanOptions.users) {
        flag = 'A'; // 清除用户数据
      } else if (this.cleanOptions.settings) {
        flag = 'B'; // 清除系统数据
      }

      if (!flag) {
        this.$message.warning('请至少选择一个要清理的选项');
        // 不关闭对话框，让用户重新选择或取消
        return;
      }

      this.cleanLoading = true;
      try {
        const response = await this.$settingapi.clearData(flag);

        if (response.code === '200') {
          this.$message.success('数据清理成功');
          this.cleanDialogVisible = false; // 清理成功后关闭对话框
          // 可选：清理后刷新相关数据
          // this.loadInitialData();
        } else {
          this.$message.error(response.msg || '数据清理失败');
        }
      } catch (error) {
        console.error('数据清理失败:', error);
        this.$message.error('数据清理失败');
      } finally {
        this.cleanLoading = false;
      }
    },

    // 处理文件选择变化
    handleFileChange(_, fileList) {
      // 忽略file参数，只使用fileList
      this.importFileList = fileList;
    },

    // 处理还原文件选择变化
    handleRestoreFileChange(_, fileList) {
      // 忽略file参数，只使用fileList
      this.restoreFileList = fileList;
    },

    // 保存微信小程序设置
    async saveWxMiniSettings() {
      try {
        const response = await axios.post('http://118.195.171.239:8081/system/saveWxMiniSettings', {
          appId: this.wxMiniForm.appId,
          appSecret: this.wxMiniForm.appSecret,
          name: this.wxMiniForm.name
        }, {
          headers: {
            'Content-Type': 'application/json'
          }
        });

        if (response.data.code === '200') {
          this.$message.success('微信小程序设置保存成功');
        } else {
          this.$message.error(response.data.msg || '微信小程序设置保存失败');
        }
      } catch (error) {
        console.error('保存微信小程序设置失败:', error);
        this.$message.error('保存微信小程序设置失败');
      }
    },

    // 保存API接口设置
    async saveApiSettings() {
      try {
        const params = {
          adress: this.apiForm.adress,
          secretKey: this.apiForm.secretKey,
          model: this.apiForm.model
        };
        const response = await this.$settingapi.saveSystemParams(params);
        if (response.code === '200') {
          this.$message.success('API接口设置保存成功');
        } else {
          this.$message.error(response.msg || '保存API接口设置失败');
        }
      } catch (error) {
        console.error('保存API接口设置失败:', error);
        this.$message.error('保存API接口设置失败');
      }
    },

    // 加载初始数据
    async loadInitialData() {
      try {
        // 加载用户列表
        await this.onQueryUser();

        // 加载微信小程序设置
        try {
          const wxResponse = await axios.get('http://118.195.171.239:8081/system/getWxMiniSettings');
          if (wxResponse.data.code === '200' && wxResponse.data.data) {
            this.wxMiniForm = {
              appId: wxResponse.data.data.appId || '',
              appSecret: wxResponse.data.data.appSecret || '',
              name: wxResponse.data.data.name || ''
            };
          }
        } catch (error) {
          console.error('加载微信小程序设置失败:', error);
        }

        // 加载API接口设置
        try {
          const apiResponse = await axios.get('http://118.195.171.239:8081/system/getApiSettings');
          if (apiResponse.data.code === '200' && apiResponse.data.data) {
            this.apiForm = {
              adress: apiResponse.data.data.adress || 'http://api.example.com',
              secretKey: apiResponse.data.data.secretKey || '',
              model: apiResponse.data.data.model || 'deepseek-r1'
            };
          }
        } catch (error) {
          console.error('加载API接口设置失败:', error);
        }
      } catch (error) {
        console.error('加载初始数据失败:', error);
      }
    },

    // 更新个人档案筛选条件等级
    async handleUpdateFilterLevel() {
      this.updateFilterLoading = true;
      try {
        const response = await this.$settingapi.updateStudentLevels();
        if (response.code === '200') {
          this.$message.success('个人档案筛选条件等级更新成功');
        } else {
          this.$message.error(response.msg || '个人档案筛选条件等级更新失败');
        }
      } catch (error) {
        console.error('更新个人档案筛选条件等级失败:', error);
        this.$message.error('更新个人档案筛选条件等级更新失败');
      } finally {
        this.updateFilterLoading = false;
      }
    },

    // 更新个人评分及排名
    async handleUpdateScoreRank() {
      this.updateScoreLoading = true;
      try {
        const response = await this.$settingapi.updateScoreAndRank();
        if (response.code === '200') {
          this.$message.success('个人评分及排名更新成功');
        } else {
          this.$message.error(response.msg || '个人评分及排名更新失败');
        }
      } catch (error) {
        console.error('更新个人评分及排名失败:', error);
        this.$message.error('更新个人评分及排名失败');
      } finally {
        this.updateScoreLoading = false;
      }
    },

    // 数据导出
    async handleExportData() {
      // 使用选中的数据类型作为module
      if (this.exportForm.dataTypes.length === 0) {
        this.$message.warning('请至少选择一种数据类型进行导出');
        return;
      }
      const module = this.exportForm.dataTypes.join(','); // 将选中的数据类型用逗号拼接
      this.exportLoading = true;
      try {
        const response = await this.$settingapi.exportExcelData(module);
        // response为blob数据
        const blob = new Blob([response], { type: 'application/vnd.ms-excel' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        // 文件名
        let fileName = '数据导出_' + module + '_' + new Date().toISOString().split('T')[0] + '.xlsx';
        link.download = fileName;
        link.click();
        URL.revokeObjectURL(link.href);
        this.$message.success('数据导出成功');
      } catch (error) {
        console.error('数据导出失败:', error);
        this.$message.error('数据导出失败');
      } finally {
        this.exportLoading = false;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.system-settings {
  width: 100%;
  height: 100%;
  padding: 20px;
  color: #d3d6dd;
  background-image: url("~@/assets/pageBg.png");
  background-size: cover;
  background-position: center center;

  // 自定义tabs样式
  .custom-tabs {
    .el-tabs__header {
      border-bottom: 1px solid rgba(104, 216, 254, 0.3);
      margin-bottom: 20px;

      .el-tabs__nav {
        border: none;

        .el-tabs__item {
          background-color: rgba(19, 25, 47, 0.6);
          border: 1px solid rgba(104, 216, 254, 0.5);
          color: #d3d6dd;
          transition: all 0.3s;
          margin-right: 5px;
          border-radius: 4px 4px 0 0;
          font-size: 16px;
          padding: 0 25px;
          height: 45px;
          line-height: 45px;
          letter-spacing: 1px;

          &:hover {
            color: #ffffff;
            background-color: rgba(104, 216, 254, 0.2);
            border-color: rgba(104, 216, 254, 0.7);
          }

          &.is-active {
            background-color: rgba(104, 216, 254, 0.2);
            border-bottom-color: transparent;
            color: #ffffff;
            font-weight: bold;
            text-shadow: 0 0 10px rgba(104, 216, 254, 0.5);
            box-shadow: 0 -2px 10px rgba(104, 216, 254, 0.3);
          }
        }
      }
    }

    .el-tabs__content {
      padding: 10px 0;
    }
  }

  // 自定义卡片样式
  .custom-card {
    background-color: rgba(19, 25, 47, 0.92);
    border: 1px solid rgba(104, 216, 254, 0.3);
    color: #d3d6dd;

    .el-card__header {
      border-bottom: 1px solid rgba(104, 216, 254, 0.3);
      padding: 15px 20px;
    }

    .el-card__body {
      padding: 20px;
    }
  }

  .card-header {
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;

    .card-title {
      font-size: 18px;
      font-weight: bold;
      color: #68d8fe;
      margin-bottom: 5px;
    }

    .card-subtitle {
      font-size: 14px;
      color: rgba(211, 214, 221, 0.7);
    }
  }

  // 自定义按钮样式
  .custom-button {
    background-color: rgba(104, 216, 254, 0.2);
    border-color: rgba(104, 216, 254, 0.5);
    color: #68d8fe;
    font-weight: bold;

    &:hover, &:focus {
      background-color: rgba(104, 216, 254, 0.3);
      border-color: rgba(104, 216, 254, 0.8);
      color: #fff;
    }
  }

  .custom-danger-button {
    background-color: rgba(245, 108, 108, 0.2);
    border-color: rgba(245, 108, 108, 0.5);
    color: #f56c6c;
    font-weight: bold;

    &:hover, &:focus {
      background-color: rgba(245, 108, 108, 0.3);
      border-color: rgba(245, 108, 108, 0.8);
      color: #fff;
    }
  }

  .add-user-btn-container {
    margin-bottom: 20px;
    text-align: right;
  }

  .add-user-btn {
    font-weight: bold;
  }

  // 自定义标签样式
  .custom-tab-label {
    color: #68d8fe;
    display: flex;
    align-items: center;
    justify-content: center;

    i {
      margin-right: 8px;
      font-size: 18px;
    }

    span {
      font-size: 16px;
      font-weight: bold;
    }
  }

  // 数据管理相关样式
  .section-label {
    color: #68d8fe;
    font-weight: bold;
    margin-bottom: 15px;
  }

  .file-upload-section {
    margin-bottom: 20px;

    .el-upload__tip {
      color: rgba(211, 214, 221, 0.7);
      margin-top: 10px;
    }

    .import-btn, .restore-btn {
      margin-top: 15px;
    }
  }

  .backup-frequency-label, .export-format-label {
    color: #68d8fe;
    font-weight: bold;
    margin-bottom: 15px;
  }

  .backup-frequency-select, .export-format-select {
    width: 100%;
    margin-bottom: 15px;
  }

  .backup-btn, .export-btn, .clean-btn {
    margin-top: 15px;
  }

  .clean-options {
    margin-bottom: 20px;

    .el-checkbox {
      display: block;
      margin-bottom: 10px;
      color: #d3d6dd;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  .data-management-container {
    max-height: 600px;
    overflow-y: auto;
    padding: 10px;

    &.scrollable-container {
      scrollbar-width: thin;
      scrollbar-color: rgba(144, 147, 153, 0.3) transparent;

      &::-webkit-scrollbar {
        width: 6px;
        height: 6px;
      }

      &::-webkit-scrollbar-thumb {
        background-color: rgba(144, 147, 153, 0.3);
        border-radius: 3px;
      }

      &::-webkit-scrollbar-track {
        background-color: transparent;
      }
    }

    .data-card {
      background-color: rgba(19, 25, 47, 0.6);
      border: 1px solid rgba(104, 216, 254, 0.2);
      border-radius: 4px;
      margin-bottom: 20px;
      transition: all 0.3s;

      &:hover {
        border-color: rgba(104, 216, 254, 0.5);
        box-shadow: 0 0 10px rgba(104, 216, 254, 0.2);
      }

      &:last-child {
        margin-bottom: 0;
      }

      .el-card__header {
        padding: 12px 20px;
        border-bottom: 1px solid rgba(104, 216, 254, 0.2);
        background-color: rgba(19, 25, 47, 0.8);

        .clearfix {
          display: flex;
          align-items: center;

          .data-card-title {
            margin-right: 10px;
            font-weight: bold;
            color: #68d8fe;
            font-size: 16px;
          }

          .el-icon-info {
            color: rgba(104, 216, 254, 0.7);
            cursor: pointer;

            &:hover {
              color: #68d8fe;
            }
          }
        }
      }

      .el-card__body {
        padding: 20px;
        text-align: center;
      }
    }

    .data-export-content {
      .module-selector {
        margin: 10px 0;
      }

      .export-form {
        max-width: 500px;
        margin: 0 auto;
        text-align: left;

        .el-form-item__label {
          color: #68d8fe;
          font-weight: bold;
        }

        .el-checkbox-group {
          display: flex;
          flex-wrap: wrap;

          .el-checkbox {
            margin-right: 20px;
            margin-bottom: 10px;

            .el-checkbox__label {
              color: #d3d6dd;
            }

            &.is-checked {
              .el-checkbox__label {
                color: #68d8fe;
              }
            }
          }
        }

        .export-btn {
          width: 100%;
          margin-top: 20px;
        }
      }
    }
  }

  // 自定义表格样式
  .custom-table {
    background-color: transparent;
    border-radius: 10px;
    box-shadow: 0 2px 16px rgba(104, 216, 254, 0.08);
    overflow: hidden;

    &::before {
      display: none;
    }

    .el-table__header-wrapper {
      th {
        background-color: rgba(104, 216, 254, 0.15);
        border-bottom: 1.5px solid rgba(104, 216, 254, 0.6);
        color: #68d8fe;
        font-weight: bold;
        font-size: 16px;
        letter-spacing: 1px;
        padding: 14px 0;
      }
    }

    .el-table__body-wrapper {
      tr {
        background-color: rgba(19, 25, 47, 0.8);
        transition: all 0.3s;

        &:hover > td {
          background-color: rgba(104, 216, 254, 0.25) !important;
        }

        td {
          border-bottom: 1px solid rgba(104, 216, 254, 0.15);
          color: #d3d6dd;
          font-size: 15px;
        }
      }
    }

    .el-table__row:last-child td {
      border-bottom: none;
    }

    .el-table--border, .el-table--group {
      border: none;
    }
    .el-table--fit {
      border-right: none;
      border-bottom: none;
    }
    .el-table__body-body {
      border-left: none;
    }
    .el-table__fixed,
    .el-table__fixed-bottom {
      left: 0;
      overflow: hidden;
      -webkit-box-shadow: none;
      box-shadow: none;
    }
  }

  // 自定义标签样式
  .custom-tag {
    border-radius: 4px;
    padding: 4px 8px;
    font-size: 12px;

    &.el-tag--danger {
      background-color: rgba(245, 108, 108, 0.2);
      border-color: rgba(245, 108, 108, 0.5);
      color: #f56c6c;
    }

    &.el-tag--success {
      background-color: rgba(103, 194, 58, 0.2);
      border-color: rgba(103, 194, 58, 0.5);
      color: #67c23a;
    }

    &.el-tag--warning {
      background-color: rgba(230, 162, 60, 0.2);
      border-color: rgba(230, 162, 60, 0.5);
      color: #e6a23c;
    }

    &.el-tag--info {
      background-color: rgba(144, 147, 153, 0.2);
      border-color: rgba(144, 147, 153, 0.5);
      color: #909399;
    }
  }

  // 自定义小按钮样式
  .custom-mini-button {
    background-color: rgba(104, 216, 254, 0.15);
    border-color: rgba(104, 216, 254, 0.4);
    color: #68d8fe;
    padding: 5px 10px;
    border-radius: 4px;

    &:hover, &:focus {
      background-color: rgba(104, 216, 254, 0.3);
      border-color: rgba(104, 216, 254, 0.6);
      color: #fff;
    }
  }

  .custom-mini-danger-button {
    background-color: rgba(245, 108, 108, 0.15);
    border-color: rgba(245, 108, 108, 0.4);
    color: #f56c6c;
    padding: 5px 10px;
    border-radius: 4px;

    &:hover, &:focus {
      background-color: rgba(245, 108, 108, 0.3);
      border-color: rgba(245, 108, 108, 0.6);
      color: #fff;
    }
  }

  // 参数表单样式
  .param-form {
    .el-form-item__label {
      color: #68d8fe;
    }

    .el-input__inner,
    .el-select .el-input__inner {
      background-color: rgba(19, 25, 47, 0.6);
      border: 1px solid rgba(104, 216, 254, 0.3);
      color: #d3d6dd;

      &:focus {
        border-color: #68d8fe;
      }
    }

    .el-input__suffix-inner i {
      color: #68d8fe;
    }

    .el-select-dropdown {
      background-color: rgba(19, 25, 47, 0.95);
      border-color: rgba(104, 216, 254, 0.3);

      .el-select-dropdown__item {
        color: #d3d6dd;

        &.hover,
        &:hover {
          background-color: rgba(104, 216, 254, 0.15);
          color: #68d8fe;
        }

        &.selected {
          color: #68d8fe;
          font-weight: bold;
        }
      }
    }
  }

  .module-container {
    height: 100%;
    display: flex;
    flex-direction: column;

    .module-header {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      background-color: rgba(19, 25, 47, 0.8);
      padding: 15px 20px;
      border-radius: 4px;
      border: 1px solid rgba(104, 216, 254, 0.3);

      .header-icon {
        font-size: 24px;
        color: #68d8fe;
        margin-right: 10px;
      }

      .header-title {
        font-size: 22px;
        font-weight: bold;
        color: #68d8fe;
      }
    }

    .module-content {
      flex: 1;

      .content-box {
        height: 100%;
        padding: 20px;
      }

      .placeholder-content {
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: rgba(19, 25, 47, 0.6);

        .text-center {
          text-align: center;

          .title {
            font-size: 24px;
            color: #68d8fe;
            margin-bottom: 15px;
          }

          .description {
            font-size: 16px;
            color: #d3d6dd;
          }
        }
      }
    }
  }

  .data-update-content {
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 12px;
    padding: 10px;
  }
  .update-btn {
    width: 100%;
    height: 44px;
    font-size: 16px;
    font-weight: bold;
    letter-spacing: 1px;
    text-align: center;
    border-radius: 8px;
    margin: 0;
  }
}

.user-list-card {
  background: rgba(19, 25, 47, 0.98);
  border-radius: 14px;
  box-shadow: 0 4px 24px rgba(104, 216, 254, 0.10);
  border: 1.5px solid rgba(104, 216, 254, 0.18);
  margin-bottom: 30px;
  padding: 0 0 20px 0;
}

.user-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 24px 10px 24px;
  border-bottom: 1px solid rgba(104, 216, 254, 0.10);

  .user-list-title {
    display: flex;
    align-items: center;
    font-size: 20px;
    color: #68d8fe;
    font-weight: bold;

    i {
      font-size: 22px;
      margin-right: 8px;
    }
  }
  .add-user-btn {
    font-weight: bold;
    background: rgba(104, 216, 254, 0.18);
    border-color: #68d8fe;
    color: #68d8fe;
    border-radius: 6px;
    &:hover {
      background: rgba(104, 216, 254, 0.28);
      color: #fff;
    }
  }
}

.user-list-table {
  background: transparent;
  border-radius: 10px;
  margin: 0 24px;
  margin-top: 18px;
  .el-table__header-wrapper th.user-list-table-header {
    background: rgba(19, 25, 47, 0.98);
    color: #68d8fe;
    font-weight: bold;
    font-size: 16px;
    border-bottom: 1.5px solid rgba(104, 216, 254, 0.18);
    letter-spacing: 1px;
  }
  .el-table__body-wrapper td.user-list-table-cell {
    background: rgba(19, 25, 47, 0.92);
    color: #d3d6dd;
    font-size: 15px;
    border-bottom: 1px solid rgba(104, 216, 254, 0.08);
  }
  .el-table__row:hover td {
    background: rgba(104, 216, 254, 0.13) !important;
  }
  .el-table__row:last-child td {
    border-bottom: none;
  }
}
</style>
